package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //参数合法性检查
        if ((StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getPhone()))
                && dto.getEquipmentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //账号密码非空时
        Map<String, Object> map = new HashMap<>();//map用来封装jwt
        if (StringUtils.isNotBlank(dto.getPhone())
                && StringUtils.isNotBlank(dto.getPassword())){
            if (dto.getType()==null){
                //return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请选择登录方式");
                dto.setType(0);
            }

            ApUser apUser = apUserMapper.selectOne(
                    Wrappers.<ApUser>lambdaQuery()
                            .eq(ApUser::getPhone, dto.getPhone())
                            .eq(ApUser::getStatus, 0)
            );
            //type 登录方式为0时  密码登录
            if (dto.getType()==0){
                if (apUser==null){
                    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
                }
                String saltPass = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                if (!saltPass.equals(apUser.getPassword())){
                    return ResponseResult.errorResult(AppHttpCodeEnum.ADUSER_NAMEORPWD_ERROR);
                }
                //封装jwt====密码和盐置空并返回
                apUser.setSalt("");
                apUser.setPassword("");
                map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                map.put("user",apUser);
                return ResponseResult.okResult(map);
            }
            //登录方式 type =1是验证码登录
            if (dto.getType()==1){
                //校对验证码
                String redisPass =(String) redisTemplate.opsForValue().get("001" + dto.getPhone());
                if (!dto.getPassword().equals(redisPass)){
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"验证码已过期");
                }
                //数据库有账号时
                if (apUser!=null){
                    apUser.setSalt("");
                    apUser.setPassword("");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user",apUser);
                    return ResponseResult.okResult(map);
                }
                //数据库无账号时 新建一个账号
                apUser=ApUser.builder()
                        .createdTime(new Date())
                        .name(dto.getPhone())
                        .phone(dto.getPhone())
                        .certification(false)
                        .identityAuthentication(false)
                        .flag((short) 0)
                        .status(false)
                        .build();
                apUserMapper.insert(apUser);
                map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                map.put("user",apUser);
                return ResponseResult.okResult(map);
            }
        }
        //账号密码为空时游客登录
        if (dto.getEquipmentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //封装游客jwt
        map.put("token",AppJwtUtil.getToken(0L));
        return ResponseResult.okResult(map);
    }
}
